package priv.lhy.sso.controller;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import priv.lhy.annotation.Anoymous;
import priv.lhy.constans.WebConstant;

import priv.lhy.constants.ResponseCodeEnum;
import priv.lhy.dto.*;
import priv.lhy.sso.controller.support.ResponseData;
import priv.lhy.user.IUserCoreService;
import priv.lhy.utils.CookieUtils;
import priv.lhy.utils.JwtTokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author : lihy
 * date : 2019/2/12 13:55
 * 用户操作控制类
 */
@RestController
public class UserController extends BaseController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    IUserCoreService userCoreService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param response
     * @return
     */
    @Anoymous
    @PostMapping("/login")
    public ResponseData doLogin(String username, String password, HttpServletResponse response) {

        UserLoginRequest request = new UserLoginRequest();
        request.setUsername(username);
        request.setPassword(password);

        //调用远程用户登录服务
        UserLoginResponse userLoginResponse = userCoreService.login(request);

        //将生成的token信息写入cookie
        response.setHeader("Set-Cookie", "access_token=" + userLoginResponse.getToken() + ";Path=/;HttpOnly");
        return getResponse(userLoginResponse.getCode(), userLoginResponse.getMsg(), WebConstant.ACTIVITY_ACCESS_URL);
    }

    /**
     * 用户注册
     *
     * @param username
     * @param password
     * @param mobile
     * @return
     */
    @Anoymous
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData register(String username, String password, String mobile, String codeText, HttpServletRequest request, HttpServletResponse response) {
        ResponseData data;
        try {
            data = new ResponseData();
            //获取验证码token
            String token = CookieUtils.getCookieValue(request, "captcha_token");
            if (StringUtils.isEmpty(token)) {
                return getResponse(ResponseCodeEnum.CAPTEXT_ERROR.getCode(), ResponseCodeEnum.CAPTEXT_ERROR.getMsg());
            }
            //获取验证码
            String capText = JwtTokenUtils.getTokenValue(token, "capText").toString();
            //比较验证码
            if (!capText.equals(codeText)) {
                //验证码错误直接返回
                data = getResponse(ResponseCodeEnum.CAPTEXT_ERROR.getCode(), ResponseCodeEnum.CAPTEXT_ERROR.getMsg());
            } else {
                UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
                userRegisterRequest.setUsername(username);
                userRegisterRequest.setPassword(password);
                userRegisterRequest.setMobile(mobile);
                try {
                    //调用远程用户注册服务
                    UserRegisterResponse userRegisterResponse = userCoreService.register(userRegisterRequest);
                    /**
                     * todo
                     * 注册成功后续操作(发短信，发邮件等等)，
                     * 通过消息中间件异步解耦
                     */
                    data = getResponse(userRegisterResponse.getCode(), userRegisterResponse.getMsg());
                    response.setHeader("Set-Cookie", "access_token=" + userRegisterResponse.getToken() + ";Path=/;HttpOnly");
                } catch (Exception e) {
                    data = getResponse(ResponseCodeEnum.SYSTEM_BUSY.getCode(), ResponseCodeEnum.SYSTEM_BUSY.getMsg());
                }
            }
        } catch (ExpiredJwtException e) {
            //token超时
            logger.error("Expire: " + e.getMessage());
            data = getResponse(ResponseCodeEnum.TOKEN_EXPIRE.getCode(), ResponseCodeEnum.TOKEN_EXPIRE.getMsg());
        } catch (SignatureException e1) {
            //签名错误
            logger.error("SignatureException: " + e1.getMessage());
            data = getResponse(ResponseCodeEnum.SIGNATURE_ERROR.getCode(), ResponseCodeEnum.SIGNATURE_ERROR.getMsg());
        } catch (Exception e2) {
            //其他异常
            logger.error("login occur exception: " + e2.getMessage());
            data = getResponse(ResponseCodeEnum.SYSTEM_BUSY.getCode(), ResponseCodeEnum.SYSTEM_BUSY.getMsg());
        }
        return data;
    }

    /**
     * 组装response
     *
     * @param code
     * @param msg
     * @param obj
     * @return
     */
    private ResponseData getResponse(String code, String msg, Object obj) {
        ResponseData response = new ResponseData();
        response.setCode(code);
        response.setMsg(msg);
        if (obj != null) {
            response.setData(obj);
        }
        return response;
    }

    /**
     * 组装response
     *
     * @param code
     * @param msg
     * @return
     */
    private ResponseData getResponse(String code, String msg) {
        return getResponse(code, msg, null);
    }
}
